package com.dm.cloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.dm.cloud.api.dto.Orders;
import com.dm.cloud.api.service.IOrderService;
import com.dm.cloud.api.service.ISeckillService;
import com.dm.cloud.common.R;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.stream.IntStream;
import java.util.stream.LongStream;

@Log4j2
@RestController
@RequestMapping("order")
public class OrderController {

    @Autowired
    private IOrderService orderService;

    @GetMapping("/search/{orderNo}")
    public R<Orders> search(@PathVariable("orderNo") String orderNo){
        log.info("get order detail,orderNo is :{}",orderNo);
        return orderService.selectByCode(orderNo);
    }

    @PostMapping("/create")
    public R<Orders> create(@RequestBody Orders orders) throws Exception {
        log.info("create order:{}", orders);
//        log.info("XID:{}", RootContext.getXID());
        return orderService.orderCreate(orders);
    }

    @Autowired
    private ISeckillService seckillService;

    /**
     * 限流
     * */
    public R<Orders> seckillFallback(Long accountId,Long pid,BlockException ex) {
        return R.failure("活动火爆，请重新尝试!");
    }

    //限时秒杀接口（通过Sentinel限流）
    @PostMapping("/seckill/{accountId}/{pid}")
    @SentinelResource(value="seckill",blockHandler = "seckillFallback")
    public R seckill(@PathVariable("accountId") Long accountId,@PathVariable("pid") Long pid) throws Exception {
        return seckillService.seckill(accountId,pid);
    }

    //秒杀订单支付接口
    @PostMapping("/killpay/{seckillOrder}")
    public R killpay(@PathVariable("seckillOrder") String seckillOrder) throws Exception {
        return seckillService.killpay(seckillOrder);
    }

    //秒杀订单支付接口
    @GetMapping("/secTest/{num}")
    public void secTest(@PathVariable("num") Integer num) throws Exception {
        LongStream.rangeClosed(1,num).parallel().boxed().forEach(
            e->{
                IntStream.rangeClosed(1,5).parallel().boxed().forEach(e1->{
                    R result = null;
                    try {
                        result = seckillService.seckill(e,1l);
                    } catch (InterruptedException interruptedException) {
                        interruptedException.printStackTrace();
                    }
                    System.out.println("account:"+e+":------"+result.getMessage());
                });
            });
    }

    @GetMapping("/payTest")
    public void payTest() throws Exception {
        seckillService.payTest();
    }
}
